<template>
  <div class="app-container customer-div" style="overflow-x: auto">
    <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
      <el-form-item label="日期：">
        <el-date-picker
          v-model="listQuery.logDate"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" label-width="0px">
        <el-radio-group v-model="type" @change="changeType">
          <el-radio-button :label="1">按品类</el-radio-button>
          <el-radio-button :label="2">按牌号</el-radio-button>
        </el-radio-group>
        <el-select
          clearable
          v-model="listQuery.categoryName"
          v-if="type == 1"
          filterable
          remote
          reserve-keyword
          allow-create
          placeholder="请输入关键词"
        >
          <el-option
            v-for="item in options"
            :key="item.categoryName"
            :label="item.categoryName"
            :value="item.categoryName"
          >
          </el-option>
        </el-select>
        <el-select
          clearable
          v-model="listQuery.sapGoodsId"
          v-if="type == 2"
          filterable
          remote
          allow-create
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in options2"
            :key="item.sapGoodsId"
            :label="item.categoryName + '/' + item.goodsSn"
            :value="item.sapGoodsId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          style="margin-left: 10px"
          @click="handleSearchList"
          type="primary"
        >
          查询
        </el-button>

        <el-button
          :loading="btnLoading"
          style="margin-left: 10px"
          @click="downloadExcel"
          type="primary"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <div
      id="warehouseChart"
      style="height: 400px; margin-top: 20px"
      v-loading="loadingChart"
    ></div>
    <!--数据列表-->
    <el-tabs v-model="activeName">
      <el-tab-pane label="成交库存明细表" name="first">
        <div class="table-container">
          <el-table
            v-loading="listLoading"
            :data="tableData"
            border
            style="width: 100%; margin-top: 20px"
            :header-cell-style="{
              background: '#fafafa',
            }"
            height="500"
          >
            <el-table-column label="日期" align="center" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.logDate }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="品类" min-width="100">
              <template slot-scope="scope">
                {{ scope.row.categoryName }}
              </template>
            </el-table-column>
            <el-table-column label="牌号" align="center" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.goodsSn }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="成交价格" align="center">
              <template slot-scope="scope">
                {{ scope.row.goodsPrice }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="采购报价" align="center">
              <template slot-scope="scope">
                {{ scope.row.purchasePrice }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="实际总库存" align="center">
              <template slot-scope="scope">
                {{ scope.row.allStock }}
              </template>
            </el-table-column>

            <el-table-column min-width="100" label="余达仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.yudaStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="运联仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.yunlianStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="塑通仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.sutongStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="外仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.otherStock }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="150"
              label="牌号可用库存"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.enableStock }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="150"
              label="品类可用库存"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.categoryEnableStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="150" label="单据号" align="center">
              <template slot-scope="scope">
                {{ scope.row.orderSn }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="pageNum"
            :page-size="pageSize"
            :page-sizes="[10, 15, 20, 50, 100]"
            :total="count"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="库存实时变化表" name="second">
        <div class="table-container">
          <el-table
            v-loading="listLoading2"
            :data="tableData2"
            border
            height="500"
            style="width: 100%; margin-top: 20px"
            :header-cell-style="{
              background: '#fafafa',
            }"
          >
            <el-table-column label="日期" align="center" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.logDate }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="品类" min-width="100">
              <template slot-scope="scope">
                {{ scope.row.categoryName }}
              </template>
            </el-table-column>
            <el-table-column label="牌号" align="center" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.goodsSn }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="类型" align="center">
              <template slot-scope="scope">
                {{ scope.row.logType }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="数量" align="center">
              <template slot-scope="scope">
                {{ scope.row.goodsNum }}
              </template>
            </el-table-column>

            <el-table-column min-width="100" label="实际总库存" align="center">
              <template slot-scope="scope">
                {{ scope.row.allStock }}
              </template>
            </el-table-column>

            <el-table-column min-width="100" label="余达仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.yudaStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="运联仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.yunlianStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="塑通仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.sutongStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="100" label="外仓" align="center">
              <template slot-scope="scope">
                {{ scope.row.otherStock }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="150"
              label="牌号可用库存"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.enableStock }}
              </template>
            </el-table-column>
            <el-table-column
              min-width="150"
              label="品类可用库存"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.categoryEnableStock }}
              </template>
            </el-table-column>
            <el-table-column min-width="150" label="单据号" align="center">
              <template slot-scope="scope">
                {{ scope.row.orderSn }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange2"
            @current-change="handleCurrentChange2"
            layout="total, sizes,prev, pager, next,jumper"
            :current-page.sync="pageNum2"
            :page-size="pageSize2"
            :page-sizes="[10, 15, 20, 50, 100]"
            :total="count2"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
const defaultListQuery = {
  logDate: [], //日期
  categoryName: "", //品类名称
  sapGoodsId: "",
  pageNum: 1,
  pageSize: 10,
};

import {
  goodsStockOrderLog,
  goodsStockOperateLog,
  goodsStockOperateReport,
  goodsSortList,
  sapGoodsList,
} from "@/api/allInLine/goods.js";
import { mapGetters } from "vuex";
import { formatDate } from "@/utils/date";
export default {
  name: "saleReport",
  data() {
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      count: 0,
      listLoading: false,
      pageNum2: 1,
      pageSize2: 10,
      tableData2: [],
      count2: 0,
      listLoading2: false,
      type: 1,
      options: [],
      options2: [],
      loading: false,
      echartsData: {},

      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "30天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      activeName: "first",
      btnLoading: false,
      loadingChart: false,
    };
  },

  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  created() {
    // let start = new Date();
    // let startDate =
    //   start.getFullYear() +
    //   "-" +
    //   (start.getMonth() + 1) +
    //   "-" +
    //   start.getDate();
    // let end = new Date();
    // let endDate =
    //   end.getFullYear() + "-" + (end.getMonth() + 1) + "-" + end.getDate();
    // this.listQuery.logDate.push(startDate, endDate);
    let now = new Date();
    let today = formatDate(now, "yyyy-MM-dd");
    this.listQuery.logDate = [today, today];
    this.getList();
    this.getList2();
    this.getChartList();
    goodsSortList().then((res) => {
      this.options = res;
    });
  },
  methods: {
    //下载excle
    downloadExcel() {
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      this.btnLoading = true;
      goodsStockOperateReport(params)
        .then((res) => {
          this.btnLoading = false;
          require.ensure([], () => {
            const { export_json_to_excel } = require("sheet/Export2Excel");
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          });
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },

    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        sapGoodsList({ keywords: query }).then((res) => {
          this.options2 = res;
          this.loading = false;
        });
      } else {
        this.options2 = [];
      }
    },
    changeType() {
      if (this.type == 1) {
        this.listQuery.sapGoodsId = "";
      } else if (this.type == 2) {
        this.listQuery.categoryName = "";
      }
    },
    //获取图表数据
    getChartList() {
      this.loadingChart = true;
      goodsStockOperateReport(this.listQuery)
        .then((res) => {
          this.echartsData = res;
          this.loadingChart = false;
          this.draw1();
        })
        .catch(() => {
          this.loadingChart = false;
        });
    },

    //画产品销量排行
    draw1() {
      let warehouseChart = this.$echarts.init(document.getElementById("warehouseChart"));
      let array = [];
      let array2 = JSON.parse(JSON.stringify(this.echartsData.priceList));
      array = this.echartsData.enableStockList.concat(
        this.echartsData.orderStockList
      );
      array = array.filter((el) => {
        return el != null;
      });
      array = array.sort((a, b) => a - b);
      array2 = array2.sort((a, b) => a - b);
      let min = array[0] ? array[0] : 0;
      let min2 = array2[0] ? array2[0] : 0;
      // 绘制图表
      warehouseChart.setOption({
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["可用库存", "成交可用库存", "成交价格"],
        },

        toolbox: {},
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.echartsData.timeList,
        },

        yAxis: [
          {
            type: "value",
            name: "库存",
            position: "left",
            min: min,
          },
          {
            type: "value",
            name: "价格",
            position: "right",
            min: min2,
          },
        ],

        series: [
          {
            name: "可用库存",
            type: "line",
            yAxisIndex: 0,
            data: this.echartsData.enableStockList,
          },
          {
            name: "成交可用库存",
            type: "line",
            yAxisIndex: 0,
            data: this.echartsData.orderStockList,
          },
          {
            name: "成交价格",
            type: "line",
            yAxisIndex: 1,
            data: this.echartsData.priceList,
          },
        ],
      });
    },

    handleSearchList() {
      this.pageNum = 1;
      this.pageNum2 = 1;
      this.getList();
      this.getList2();
      this.getChartList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let data = JSON.parse(JSON.stringify(this.listQuery));
      data.pageNum = this.pageNum;
      data.pageSize = this.pageSize;
      goodsStockOrderLog(data)
        .then((response) => {
          this.tableData = response.list;
          this.count = response.count;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },

    //获取列表
    getList2() {
      this.listLoading2 = true;
      let data = JSON.parse(JSON.stringify(this.listQuery));
      data.pageNum = this.pageNum2;
      data.pageSize = this.pageSize2;
      goodsStockOperateLog(data)
        .then((response) => {
          this.tableData2 = response.list;
          this.count2 = response.count;
          this.listLoading2 = false;
        })
        .catch(() => {
          this.listLoading2 = false;
        });
    },

    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },

    handleSizeChange2(val) {
      this.pageNum2 = 1;
      this.pageSize2 = val;
      this.getList2();
    },
    handleCurrentChange2(val) {
      this.pageNum2 = val;
      this.getList2();
    },
  },
};
</script>

<style scoped lang="scss">
</style>
